import axios from 'axios'
import router from "@/router";
import { showNotify, showLoadingToast, closeToast, showFailToast } from 'vant'
import { localStorage } from '@/utils/local-storage'
import errorCode from "@/utils/errorCode";
import img_index_path from '~/loading.gif';

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: true })

import i18n from "@/locales";

const { t }: any = i18n.global

import { STORAGE_LANG_KEY, STORAGE_TOKEN_KEY, STORAGE_USER_DATA_KEY } from '@/stores/mutation-type'

export const REQUEST_TOKEN_KEY = STORAGE_TOKEN_KEY
export const REQUEST_LANG_KEY = 'locale'
export const REQUEST_TIMEOUT = 6000 * 2

const request = axios.create({
    baseURL: process.env.VUE_APP_API_URL,
    timeout: REQUEST_TIMEOUT,
})

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        NProgress.start();
        showLoadingToast({
            icon: img_index_path,
            className: 'bg-transparent',
            // overlay: true,
            duration: 0, // 持续展示 toast
            forbidClick: true,
            loadingType: 'spinner',
        })
        const savedToken = localStorage.get(STORAGE_TOKEN_KEY)
        if (savedToken) config.headers[REQUEST_TOKEN_KEY] = 'Bearer ' + savedToken
        const language = localStorage.get(STORAGE_LANG_KEY)
        if (language) config.headers[REQUEST_LANG_KEY] = language
        config.withCredentials = true
        config['requestId'] = btoa(new Date().toJSON())
        console.log('%c                                      BEGIN: ' + config['requestId'] + '[TIMEOUT: ' + REQUEST_TIMEOUT + ']                                      ', 'background:#ff976a;color:#fff;')
        console.log('%c [' + config.url + '] ' + config.method.toUpperCase() + ':', 'color:#ff976a;', process.env.VUE_APP_PUBLIC_PATH + process.env.VUE_APP_API_BASE_URL + config.url)
        console.log('💯[' + config.url + '] data:', config.data)
        console.log('💯[' + config.url + '] headers:', config.headers)
        // console.log('💯['+process.env.VUE_APP_API_BASE_URL+config.url+'] all:',config)
        return config
    },
    (error) => {
        showNotify({ type: 'danger', message: error })
    }
)

// 响应拦截器
request.interceptors.response.use(
    async (response) => {
        NProgress.done()
        closeToast()
        const code = response.data.returnCode || 10000
        const msg = errorCode[code] || response.data.returnMsg || errorCode['default']
        // 二进制数据则直接返回
        if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
            return response.data
        }
        if (code === 10001) {
            localStorage.remove(STORAGE_TOKEN_KEY)
            localStorage.remove(STORAGE_USER_DATA_KEY)
            router.push('/login')
            showNotify({ type: 'danger', message: t('login.loginTimeOut') })
            return Promise.reject('Authorization verification failed')
        } else if (code === 99999) {
            const time = msg.length * 120
            showFailToast({
                message: msg,
                duration: time > 2000 && time < 5000 ? time : (time < 2000 ? 2000 : 5000)
            })
            return Promise.reject(new Error(msg))
        } else if (code !== 10000) {
            showNotify({ type: 'danger', message: msg })
            return Promise.reject('error')
        } else {
            console.log('%c [' + response.config.url + '] RESPONSE:' + response.data.status, response.data.status != 200 ? 'color:red;' : 'color:#07c160;', response.data)
            console.log('%c                                      END: ' + response.config['requestId'] + '                                      ', 'background:#ff976a;color:#fff;')
            return response.data
        }
    },
    (error): Promise<any> => {
        NProgress.done()
        closeToast()
        console.log('err' + error)
        let { message } = error
        if (message === 'Network Error') {
            message = t('system.backError')
        } else if (message.includes('timeout')) {
            message = t('system.interfaceTimeOut')
        } else if (message.includes('Request failed with status code')) {
            message = t('system.interface') + message.substr(message.length - 3) + t('system.abnormal')
        }
        showNotify({ message: message, type: 'danger', duration: 5 * 1000 })
        return Promise.reject(error)
    }
)

export default request
